import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import json
import os
from pathlib import Path

class QuizApp:
    def __init__(self, root):
        self.root = root
        self.root.title("商业察言观色能力训练系统")
        self.root.geometry("1200x800")
        
        # 数据变量
        self.questions = []
        self.current_question_index = 0
        self.selected_file = None
        self.selected_option = None
        self.completed_files = self.load_completed_files()  # 加载已完成的文件记录
        self.completed_count = self.load_completed_count()  # 加载已完成的题目套数
        
        # 创建界面
        self.create_widgets()
        
        # 填充文件列表
        self.populate_file_list()
        
    def center_window(self, window, width, height):
        """
        将窗口居中显示
        """
        # 获取屏幕尺寸
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()
        
        # 计算居中位置
        x = (screen_width // 2) - (width // 2)
        y = (screen_height // 2) - (height // 2)
        
        window.geometry(f'{width}x{height}+{x}+{y}')
        
    def load_completed_files(self):
        """
        加载已完成的题目文件记录
        """
        completed = set()
        try:
            if os.path.exists("completed_files.txt"):
                with open("completed_files.txt", "r", encoding="utf-8") as f:
                    for line in f:
                        completed.add(line.strip())
        except Exception as e:
            print(f"加载完成记录时出错: {e}")
        return completed
        
    def load_completed_count(self):
        """
        加载已完成的题目套数记录
        """
        try:
            if os.path.exists("completed_count.txt"):
                with open("completed_count.txt", "r", encoding="utf-8") as f:
                    return int(f.read().strip())
        except Exception as e:
            print(f"加载完成套数记录时出错: {e}")
        return 0
        
    def save_completed_count(self):
        """
        保存已完成的题目套数记录
        """
        try:
            with open("completed_count.txt", "w", encoding="utf-8") as f:
                f.write(str(self.completed_count))
        except Exception as e:
            print(f"保存完成套数记录时出错: {e}")
        
    def save_completed_file(self, filename):
        """
        保存已完成的题目文件记录
        """
        try:
            with open("completed_files.txt", "a", encoding="utf-8") as f:
                f.write(filename + "\n")
            self.completed_files.add(filename)
            # 增加完成套数并保存
            self.completed_count += 1
            self.save_completed_count()
            # 更新文件列表显示
            self.populate_file_list()
        except Exception as e:
            print(f"保存完成记录时出错: {e}")
            
    def is_file_completed(self, filename):
        """
        检查文件是否已完成
        """
        return filename in self.completed_files

    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(2, weight=1)
        
        # 文件选择区域
        file_frame = ttk.LabelFrame(main_frame, text="选择题目文件", padding="10")
        file_frame.grid(row=0, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        file_frame.columnconfigure(1, weight=1)
        
        ttk.Label(file_frame, text="题目文件:").grid(row=0, column=0, sticky=tk.W, padx=(0, 5))
        
        self.file_var = tk.StringVar()
        self.file_combo = ttk.Combobox(file_frame, textvariable=self.file_var, state="readonly", width=50)
        self.file_combo.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(0, 5))
        
        self.load_btn = ttk.Button(file_frame, text="加载题目", command=self.load_selected_file)
        self.load_btn.grid(row=0, column=2, padx=(5, 0))
        
        # 显示完成套数
        ttk.Label(file_frame, text=f"已完成 {self.completed_count} 套题目").grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=(5, 0))
        
        # 导航区域
        nav_frame = ttk.Frame(main_frame)
        nav_frame.grid(row=1, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=(0, 10))
        nav_frame.columnconfigure(1, weight=1)
        
        self.prev_btn = ttk.Button(nav_frame, text="上一题", command=self.show_previous_question, state="disabled")
        self.prev_btn.grid(row=0, column=0, padx=(0, 5))
        
        self.progress_var = tk.StringVar()
        self.progress_label = ttk.Label(nav_frame, textvariable=self.progress_var, font=("Arial", 10, "bold"))
        self.progress_label.grid(row=0, column=1)
        
        self.next_btn = ttk.Button(nav_frame, text="下一题", command=self.show_next_question, state="disabled")
        self.next_btn.grid(row=0, column=2, padx=(5, 0))
        
        # 题目显示区域
        quiz_frame = ttk.LabelFrame(main_frame, text="题目详情", padding="10")
        quiz_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        quiz_frame.columnconfigure(0, weight=1)
        quiz_frame.rowconfigure(11, weight=1)  # 解析区域可以扩展
        
        # 题目信息
        info_frame = ttk.Frame(quiz_frame)
        info_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        info_frame.columnconfigure((0, 1, 2), weight=1)
        
        self.scenario_var = tk.StringVar()
        self.dimension_var = tk.StringVar()
        self.complexity_var = tk.StringVar()
        
        ttk.Label(info_frame, textvariable=self.scenario_var, font=("Arial", 9, "bold")).grid(row=0, column=0, sticky=tk.W)
        ttk.Label(info_frame, textvariable=self.dimension_var, font=("Arial", 9, "bold")).grid(row=0, column=1, sticky=tk.W)
        ttk.Label(info_frame, textvariable=self.complexity_var, font=("Arial", 9, "bold")).grid(row=0, column=2, sticky=tk.W)
        
        # 情境描述
        ttk.Label(quiz_frame, text="情境描述:", font=("Arial", 10, "bold")).grid(row=1, column=0, sticky=tk.W, pady=(10, 0))
        self.scenario_text = scrolledtext.ScrolledText(quiz_frame, height=3, wrap=tk.WORD, state="disabled")
        self.scenario_text.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 关键观察点
        ttk.Label(quiz_frame, text="关键观察点:", font=("Arial", 10, "bold")).grid(row=3, column=0, sticky=tk.W, pady=(10, 0))
        self.key_points_text = scrolledtext.ScrolledText(quiz_frame, height=3, wrap=tk.WORD, state="disabled")
        self.key_points_text.grid(row=4, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 问题
        ttk.Label(quiz_frame, text="问题:", font=("Arial", 10, "bold")).grid(row=5, column=0, sticky=tk.W, pady=(10, 0))
        self.question_text = scrolledtext.ScrolledText(quiz_frame, height=3, wrap=tk.WORD, state="disabled")
        self.question_text.grid(row=6, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 选项
        ttk.Label(quiz_frame, text="选项:", font=("Arial", 10, "bold")).grid(row=7, column=0, sticky=tk.W, pady=(10, 0))
        self.options_frame = ttk.Frame(quiz_frame)
        self.options_frame.grid(row=8, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
        self.options_frame.columnconfigure(0, weight=1)
        
        # 反馈
        self.feedback_var = tk.StringVar()
        self.feedback_label = ttk.Label(quiz_frame, textvariable=self.feedback_var, font=("Arial", 10, "bold"))
        self.feedback_label.grid(row=9, column=0, pady=(10, 0))
        
        # 解析（增大文本框）
        ttk.Label(quiz_frame, text="答案与解析:", font=("Arial", 10, "bold")).grid(row=10, column=0, sticky=tk.W, pady=(10, 0))
        self.explanation_text = scrolledtext.ScrolledText(quiz_frame, height=12, wrap=tk.WORD, state="disabled")  # 增加高度到12行
        self.explanation_text.grid(row=11, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
        
        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=3, column=0, columnspan=3, pady=(10, 0))
        
        self.show_answer_btn = ttk.Button(button_frame, text="查看答案", command=self.show_answer, state="disabled")
        self.show_answer_btn.pack(side=tk.LEFT, padx=(0, 10))
        
        self.reset_btn = ttk.Button(button_frame, text="重置选择", command=self.reset_question, state="disabled")
        self.reset_btn.pack(side=tk.LEFT)
        
    def populate_file_list(self):
        # 获取所有题目文件
        files = []
        parsed_dir = Path("parsed_questions")
        if parsed_dir.exists():
            for file_path in parsed_dir.glob("questions_*.json"):
                filename = str(file_path)
                # 检查是否已完成
                if self.is_file_completed(filename):
                    files.append(filename + " (已完成)")
                else:
                    files.append(filename)
            files.sort()  # 按文件名排序
        
        self.file_combo['values'] = files
        if files:
            self.file_combo.current(0)
            
    def load_selected_file(self):
        selected_file = self.file_var.get()
        # 移除"(已完成)"后缀以获取实际文件名
        actual_file = selected_file.replace(" (已完成)", "")
        
        if not actual_file:
            self.show_centered_message("警告", "请选择一个题目文件")
            return
            
        try:
            with open(actual_file, 'r', encoding='utf-8') as f:
                self.questions = json.load(f)
                
            if not self.questions:
                self.show_centered_message("警告", "选中的文件中没有题目")
                return
                
            self.current_question_index = 0
            self.selected_file = actual_file
            self.show_question(0)
            
            # 启用导航和操作按钮
            self.prev_btn['state'] = 'normal'
            self.next_btn['state'] = 'normal'
            self.show_answer_btn['state'] = 'normal'
            self.reset_btn['state'] = 'normal'
            
            self.show_centered_message("成功", f"成功加载 {len(self.questions)} 道题目")
            
        except Exception as e:
            self.show_centered_message("错误", f"加载题目文件时出错:\n{str(e)}")
            
    def show_centered_message(self, title, message):
        """
        显示居中的消息弹窗
        """
        # 创建顶层窗口
        top = tk.Toplevel(self.root)
        top.title(title)
        
        # 设置窗口大小并居中
        self.center_window(top, 300, 150)
        
        # 确保弹窗在最前面
        top.transient(self.root)
        top.grab_set()
        
        # 添加消息和按钮
        ttk.Label(top, text=message, wraplength=250).pack(pady=20)
        ttk.Button(top, text="确定", command=top.destroy).pack(pady=10)
        
        # 等待窗口关闭
        top.wait_window()
            
    def show_question(self, index):
        if not self.questions or index < 0 or index >= len(self.questions):
            return
            
        self.current_question_index = index
        question = self.questions[index]
        
        # 更新进度
        self.progress_var.set(f"第 {index + 1} 题 / 共 {len(self.questions)} 题")
        
        # 更新题目信息
        self.scenario_var.set(f"场景: {question.get('scenario_type', '')}")
        self.dimension_var.set(f"维度: {question.get('dimension', '')}")
        self.complexity_var.set(f"复杂度: {question.get('complexity', '')}")
        
        # 更新文本内容
        self.update_text_widget(self.scenario_text, question.get('scenario', ''))
        self.update_text_widget(self.key_points_text, question.get('key_points', ''))
        self.update_text_widget(self.question_text, question.get('question', ''))
        self.update_text_widget(self.explanation_text, question.get('explanation', ''))
        
        # 清空选项框架
        for widget in self.options_frame.winfo_children():
            widget.destroy()
            
        # 创建选项
        self.selected_option = None
        options = question.get('options', {})
        self.option_var = tk.StringVar()  # 添加这行来管理选项变量
        for i, (key, value) in enumerate(options.items()):
            option_frame = ttk.Frame(self.options_frame)
            option_frame.grid(row=i, column=0, sticky=(tk.W, tk.E), pady=2)
            option_frame.columnconfigure(1, weight=1)
            
            radio_btn = ttk.Radiobutton(
                option_frame, 
                text=f"{key}. {value}", 
                variable=self.option_var,  # 使用统一的变量
                value=key,
                command=lambda k=key: self.select_option(k)
            )
            radio_btn.grid(row=0, column=0, sticky=tk.W)
            
        # 重置反馈
        self.feedback_var.set("")
        self.feedback_label.configure(foreground="black")
        
        # 隐藏解析
        self.explanation_text.grid_remove()
        
        # 更新导航按钮状态
        self.prev_btn['state'] = 'disabled' if index == 0 else 'normal'
        self.next_btn['state'] = 'disabled' if index == len(self.questions) - 1 else 'normal'
        
        # 如果是最后一题，标记文件为已完成
        if index == len(self.questions) - 1 and self.selected_file:
            self.save_completed_file(self.selected_file)
        
    def update_text_widget(self, widget, text):
        widget.configure(state="normal")
        widget.delete(1.0, tk.END)
        widget.insert(tk.END, text)
        widget.configure(state="disabled")
        
    def select_option(self, option):
        self.selected_option = option
        
        # 检查答案
        question = self.questions[self.current_question_index]
        correct_answer = question.get('answer', '')
        
        if option == correct_answer:
            self.feedback_var.set("回答正确！")
            self.feedback_label.configure(foreground="green")
            # 显示解析
            self.explanation_text.grid()
        else:
            self.feedback_var.set("回答错误，请再试一次！")
            self.feedback_label.configure(foreground="red")
            # 隐藏解析
            self.explanation_text.grid_remove()
            
    def show_answer(self):
        if not self.questions:
            return
            
        question = self.questions[self.current_question_index]
        correct_answer = question.get('answer', '')
        
        # 设置正确答案为选中状态
        self.option_var.set(correct_answer)
        
        # 显示解析
        self.explanation_text.grid()
        
        # 更新反馈
        if self.selected_option == correct_answer:
            self.feedback_var.set("回答正确！")
            self.feedback_label.configure(foreground="green")
        elif self.selected_option:
            self.feedback_var.set(f"正确答案是: {correct_answer}")
            self.feedback_label.configure(foreground="blue")
        else:
            self.feedback_var.set(f"正确答案是: {correct_answer}")
            self.feedback_label.configure(foreground="blue")
            
    def reset_question(self):
        self.selected_option = None
        self.option_var.set("")  # 重置选项变量
        self.feedback_var.set("")
        self.feedback_label.configure(foreground="black")
        self.explanation_text.grid_remove()
        
        # 重新显示题目以重置选项
        self.show_question(self.current_question_index)
        
    def show_previous_question(self):
        if self.current_question_index > 0:
            self.show_question(self.current_question_index - 1)
            
    def show_next_question(self):
        if self.current_question_index < len(self.questions) - 1:
            self.show_question(self.current_question_index + 1)

def main():
    root = tk.Tk()
    app = QuizApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()